package cn.yunhe.crm.controller;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


import cn.yunhe.crm.annotation.SystemLog;
import cn.yunhe.crm.entity.Aproduct;
import cn.yunhe.crm.entity.Bproduct;
import cn.yunhe.crm.entity.Contract;
import cn.yunhe.crm.entity.Cproduct;
import cn.yunhe.crm.entity.Organization;
import cn.yunhe.crm.service.AproductService;
import cn.yunhe.crm.service.BproductService;
import cn.yunhe.crm.service.ContractService;
import cn.yunhe.crm.service.CproductService;
import cn.yunhe.crm.service.OrganizationService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
 * 
 * @author 尹明泉
 *	合同管理器
 */
@Scope("prototype")
@Controller
public class ContractController {
	/**
	 * 自动装配合同服务接口
	 */
	@Autowired
//合同服务接口
	@Qualifier("ContractService")
	private ContractService contractbiz;
	public void setContractbiz(ContractService contractbiz) {
		this.contractbiz = contractbiz;
	}

	@Autowired
	@Qualifier("OrganizationService") //机构服务接口
	private OrganizationService organizationbiz;
	public void setOrganizationbiz(OrganizationService organizationbiz) {
		this.organizationbiz = organizationbiz;
	}
	@Autowired
	@Qualifier("aproductbiz") //A产品接口
	private AproductService aproductbiz;
	public void setAproductbiz(AproductService aproductbiz) {
		this.aproductbiz = aproductbiz;
	}
	@Autowired
	@Qualifier("bproductbiz") //B产品接口
	private BproductService bproductbiz;
	public void setBproductbiz(BproductService bproductbiz) {
		this.bproductbiz = bproductbiz;
	}
	@Autowired
	@Qualifier("cproductbiz") //C产品接口
	private CproductService cproductbiz;
	public void setCproductbiz(CproductService cproductbiz) {
		this.cproductbiz =cproductbiz;
	}
	/**
	 * 合同集合信息
	 * @param 把合同集合(关联着机构和联系人集合)放进model ：contracts
	 * @return	
	 */
	@RequestMapping("/contractmanage.do")
	public String contract(Model model) {
		List list=contractbiz.contractlist(null);
		model.addAttribute("contracts", list);
		return "contractmanage";
	}
	/**
	 * 去新增页面
	 * @return
	 */
	@RequestMapping("/contractmanage_toadd.do")
	public String toAdd() {
		return "contractmanage_add";
	}
	/**
	 * 新增合同-同时新增关联的产品Aproduct,Bproduct,Cproduct
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("/contractmanage_add.do")
	@SystemLog(des="新增合同")
	public String Add(Contract contract,@RequestParam MultipartFile myfile, HttpServletRequest request) throws IOException {
		//如果只是上传一个文件，则只需要MultipartFile类型接收文件即可，而且无需显式指定@RequestParam注解 
        //如果想上传多个文件，那么这里就要用MultipartFile[]类型来接收文件，并且还要指定@RequestParam注解 
        //并且上传多个文件时，前台表单中的所有<input type="file"/>的name都应该是myfiles，否则参数里的myfiles无法获取到所有上传的文件 
            if(myfile.isEmpty()){ 
                System.out.println("文件未上传"); 
            }else{ 
                System.out.println("文件长度: " + myfile.getSize()); 
                System.out.println("文件类型: " + myfile.getContentType()); 
                System.out.println("文件名称: " + myfile.getName()); //此处为myfile
                System.out.println("文件原名: " + myfile.getOriginalFilename()); //此处为文件的完整名称（包含扩展名）
                System.out.println("========================================"); 
                //如果用的是Tomcat服务器，则文件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\WEB-INF\\upload\\文件夹中
                //例如此处realPath：E:\workspace\CRM\src\main\webapp\WEB-INF\ upload
                String realPath = request.getSession().getServletContext().getRealPath("/WEB-INF/upload"); 
                //这里不必处理IO流关闭的问题，因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉，我是看它的源码才知道的 
                FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(realPath, myfile.getOriginalFilename())); 
                //把文件完整路径放入contract
                contract.setFile(realPath+"\\"+myfile.getOriginalFilename());
            } 
      //保存并获得合同ID给产品外键coid        
		int coid=contractbiz.addcontract(contract);
		//产品不为空才创建产品信息，插入数据错误跳到ERROR页面
		if (contract.getAproduct() != 0) {
			Aproduct aproduct=contract.getProducta();
			aproduct.setCoid(coid);
			int i=aproductbiz.addaproduct(aproduct);
			if (i==0) {return "error";}
		}
		if (contract.getBproduct() != 0) {
			Bproduct bproduct=contract.getProductb();
			bproduct.setCoid(coid);
			int i=bproductbiz.addbproduct(bproduct);
			if (i==0) {return "error";}
		}
		if (contract.getCproduct() != 0) {
			Cproduct cproduct=contract.getProductc();
			cproduct.setCoid(coid);
			int i=cproductbiz.addcproduct(cproduct);
			if (i==0) {return "error";}
		}
		return "redirect:/contractmanage.do";
	}
	/**
	 * 	查看单个合同信息
	 * @param  id 页面的合同ID
	 * @param 把单个合同表(关联着机构和联系人)放进model ：contract
	 * @return
	 */
	@RequestMapping("/contract_detail.do")
	public String detail(Integer id ,Model model) {
		//通过ID查到单个合同
		List<Contract> list=contractbiz.contractlist(id);
		if (list.size()>0) {
			model.addAttribute("contract", list.get(0));
		}
		return "contract_detail";
	}
	/**
	 *  基于ResponseEntity实现下载功能
	 * @param request
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/filedown.do")
	@SystemLog(des="下载合同文档")
	public ResponseEntity<byte[]> download(HttpServletRequest request,HttpServletResponse response,@RequestParam("id") Integer id) throws IOException {
		List<Contract> list=contractbiz.contractlist(id);
		String path=list.get(0).getFile();
	    File file = new File(path);
		HttpHeaders headers = new HttpHeaders();
		String fileName=new String(file.getName().getBytes("UTF-8"),"iso-8859-1");//为了解决中文名称乱码问题  
		headers.setContentDispositionFormData("attachment", fileName);   
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);   
		return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);  
			
	}
	/**
	 * 	跳转到修改合同页
	 * @param  id 页面的合同ID
	 * @param 把单个合同表(关联着机构和联系人)放进model ：contract
	 * @return
	 */
	@RequestMapping("/contract_update.do")
	public String toupdate(Integer id ,Model model) {
		//根据ID查到对应的合同
		List list=contractbiz.contractlist(id);
		if (list.size()>0) {
			Contract contract=(Contract) list.get(0);
			//查找对应机构，吧机构联系人信息放进model
			List<Organization> list2=organizationbiz.findAllOrganization();
			Organization organization =new Organization();
			for (Organization organization2 : list2) {
				if (organization2.getId()==contract.getOrganization().getId()) {
					organization=organization2;
					break;
				}
			}
			model.addAttribute("organization", organization);
			//判定是否有某个产品，有就查询，放进contract
			if (contract.getAproduct()>0) {
				Aproduct aproduct=aproductbiz.getAproByCOid(id);
				contract.setProducta(aproduct);
			}
			if (contract.getBproduct()>0) {
				Bproduct bproduct=bproductbiz.getBproByCOid(id);
				contract.setProductb(bproduct);
			}
			if (contract.getCproduct()>0) {
				Cproduct cproduct=cproductbiz.getCproByCOid(id);
				contract.setProductc(cproduct);
			}
			//吧合同信息放进model里
			model.addAttribute("contract", contract);
		}
		return "contract_update";
	}
	/**
	 *  修改合同详情
	 * @param contract
	 * @return
	 */
	@RequestMapping("/docontractupdate.do")
	@SystemLog(des="修改合同详情")
	public String update(Contract contract){
		//判定是否有某个产品，有就修改
		if (contract.getAproduct() != 0) {
			Aproduct aproduct=contract.getProducta();
			aproduct.setCoid(contract.getId());
			int i=aproductbiz.updateApro(contract.getProducta());
			if (i==0) {return "error";}
		}
		if (contract.getBproduct() != 0) {
			Bproduct bproduct=contract.getProductb();
			bproduct.setCoid(contract.getId());
			int i=bproductbiz.updateBpro(contract.getProductb());
			if (i==0) {return "error";}
		}
		if (contract.getCproduct() != 0) {
			Cproduct cproduct=contract.getProductc();
			cproduct.setCoid(contract.getId());
			int i=cproductbiz.updateCpro(contract.getProductc());
			if (i==0) {return "error";}
		}
		//修改合同
		int u=contractbiz.updatecontract(contract);
		if (u==0) { //失败回到失败页面
			return "error";
		}
		return "redirect:/contractmanage.do";
	}
	/**
	 * 修改合同删除状态为：删除
	 * @param id
	 * @return
	 */
	@RequestMapping("/contractdel.do")
	@SystemLog(des="删除合同")
	public String delContract(Integer id) {
		//根据ID查到对应的合同
		List<Contract> list=contractbiz.contractlist(id);
		if (list.size()>0) {
			contractbiz.delcontract(list.get(0));
		}
		return "redirect:/contractmanage.do";
	}
	/**
	 * 异步查找机构
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/checkoid.do")
	public JSONArray checkoid() {
		List<Organization> list=organizationbiz.findAllOrganization();
		//Map map=new HashMap();
		List list2=new ArrayList();
		if (list.size()>0) {
			for (Organization organization : list) {
				Map map=new HashMap();
				map.put("name", organization.getName());
				map.put("cname", organization.getContact().getName());
				map.put("cename", organization.getContact().getEname());
				map.put("oid", organization.getId());
				list2.add(map);
			}
		}
		return JSONArray.fromObject(list2);
	}
	
}
